package com.cwz.springboot.crawlerfirst.crawler.post;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class HttpPostJsonParamTest {
    public static void main(String[] args) throws UnsupportedEncodingException {

        // 1. 打开浏览器，创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 2. 输入网址，发起get请求并创建HttpPost对象
        HttpPost httpPost = new HttpPost("http://106.15.37.148/myparnet/login");

        // 创建一个JSON的参数
        String json = "{\"username\":\"cwz\",\"password\":\"123\",\"role\":\"1\"}";
        StringEntity stringEntity = new StringEntity(json);

        // 设置表单的Entity对象到Post请求中
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.setEntity(stringEntity);

        CloseableHttpResponse response = null;

        try {
            // 3. 按回车，发起请求，返回响应，使用HttpClient对象发起请求
            response = httpClient.execute(httpPost);

            // 4. 解析响应，获取数据
            // 判断状态码是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                String content = EntityUtils.toString(httpEntity, "utf8");
                System.out.println("响应报文的长度：" + content.length());
                System.out.println(content);
                System.out.println("这是带参数(Json参数)的post请求");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 5. 关闭httpClient
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
